﻿using Autofac;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wings.Web.Repostory;

namespace Wings.Web
{
    public class NhibernateModule:Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            if (builder == null)
            {
                throw new AggregateException("builder");
            }
            //builder.RegisterGeneric(typeof(Repostory<>))
            //    .As(typeof(IRepostory<>))
            //    .InstancePerMatchingLifetimeScope(Autofac.Core.Lifetime.MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var connectionString = ConfigurationManager.ConnectionStrings["Wings"].ConnectionString;
            SessionSetup sessionSetup = new SessionSetup(connectionString);
            var sessionFactory = sessionSetup.GetSessionFactory();

          
            builder.RegisterInstance(sessionFactory);

            // Either use a session in view model or per instance depending on the context.
            //if (HttpContext.Current != null)
            //{
            //    builder.Register(s => s.Resolve<ISessionFactory>().OpenSession()).InstancePerHttpRequest();
            //}
            //else
            //{
                builder.Register(s => s.Resolve<ISessionFactory>().OpenSession()).InstancePerRequest();
            //}

            builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
       .Where(t => t.Name.EndsWith("Repostory"))
       .AsImplementedInterfaces()
       .InstancePerLifetimeScope();
            //base.Load(builder);
        }
    }
}

